package com.itheima.reggie.common;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.sql.SQLIntegrityConstraintViolationException;

@Component
@RestControllerAdvice
//全局异常处理器
public class CommonExceptionResolver {
    //用来指定拦截哪一类型的异常
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R handlerExceptionResolver1( SQLIntegrityConstraintViolationException e){
        // 处理异常的具体做法
        //打印异常信息
        e.printStackTrace();
        //Duplicate entry 'wangwu' for key 'idx_username'
        if(e.getMessage().contains("Duplicate entry")){
            String message = e.getMessage();
            String[] split = message.split("'");
            String msg = split[1] + "已存在";
            return R.error(msg);
        }
       return R.error("未知错误");
    }
    //自定义异常处理器
    @ExceptionHandler(BusinessException.class)
    public R handlerExceptionResolver2(BusinessException e){

        return R.error(e.getMessage());
    }

}
